<?php
/**
 * Created by PhpStorm.
 * User: yh
 * Date: 2018/12/19
 * Time: 下午3:21
 */
namespace app\admin\controller;

use think\Cache;
use think\Exception;
use think\Db;
use app\common\model\Order as commonorder;
use app\common\model\User;
use app\common\model\Message;
class Lottery extends Common
{
    //商品列表
    public function index()
    {
        $this->templateTitle('抽奖商品');
        $this->assign('typeList',config('lottery_type'));
        //判断条件
        $where = [];

        $id = trim(request()->param('id'));
        $this->assign('id',$id);
        if(!empty($id)){
            $where['id'] = intval($id);
        }

        //商品标题
        $title = request()->param("title");
        $this->assign("title", $title);
        if ($title)
        {
            $where["title|goods_title"] = ["LIKE", "%$title%"];
        }

        //所属分类
        $type = trim(request()->param('type'));
        $this->assign('type',$type);
        if($type){
            $where['type'] = intval($type);
        }

        //是否显示
        $is_visible = trim(request()->param('is_visible'));
        $this->assign('is_visible',$is_visible);
        if($is_visible!=''){
            $where['is_visible'] = intval($is_visible);
        }

        //获取商品列表
        $list = Db::name("lottery")
            ->where($where)
            ->paginate(15);

        $this->assign("list", $list);

        $gl = Db::name("lottery")
            ->where('is_visible',1)
            ->where('stock','gt',0)
            ->sum('gl');
        $this->assign('gl',$gl);

        return $this->fetch();
    }

    //更改
    public function visible()
    {
        if (request()->isAjax())
        {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("status");

            try
            {
                //修改菜单显示隐藏
                $save = Db::name("lottery")
                    ->where("id", $id)
                    ->update(["is_visible"=>$status,'update_time'=>now_datetime()]);
                if($status==1){
                    $log = '显示-抽奖商品-'.$id;
                }else{
                    $log = '隐藏-抽奖商品-'.$id;
                }

                if($save){
                    save_log($log);
                    $this->ajaxSuccess($log.'成功！');

                }else{
                    save_log($log,0);
                    $this->ajaxError($log.'失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //添加商品
    public function add()
    {
        if (request()->isGet())
        {
            $this->layoutModal();
            $this->assign('typeList',config('lottery_type'));
            return $this->fetch();
        }

        if (request()->isAjax())
        {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime(),
            );

            $data["title"] = trim(request()->param("title"));
            if(empty($data['title'])){
                $this->ajaxError('请输入奖名称');
            }

            $data["goods_title"] = trim(request()->param("goods_title"));
            if(empty($data['goods_title'])){
                $this->ajaxError('请输入商品名称');
            }

            $data["price_title"] = trim(request()->param("price_title"));
            if(empty($data['price_title'])){
                $this->ajaxError('请输入中奖提示词');
            }

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if(empty($data['img_url'])){
                $this->ajaxError('请上传商品缩略图');
            }

            $data["type"] = intval(request()->param("type"));
            if(empty($data['type'])){
                $this->ajaxError('请选择商品类型');
            }

            $data["num"] = intval(request()->param("num"));
            if($data['num']<0){
                $this->ajaxError('商品数值最小1');
            }

            $data["gl"] = intval(request()->param("gl"));
            if($data['gl']<0){
                $this->ajaxError('中奖比重最小0');
            }

            $data["stock"] = intval(request()->param("stock"));
            if($data['stock']<0){
                $this->ajaxError('商品库存最小0');
            }

            //显示隐藏
            $data['is_visible'] = intval(request()->param('is_visible'));

            try
            {
                $goods_id = Db::name("lottery")->insertGetId($data);
                $log = '添加-抽奖商品';
                if($goods_id){

                    $log.='-'.$goods_id;
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功');
                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }

            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function edit()
    {
        $id = intval(input('id'));
        $info = Db::name('lottery')->where('id',$id)->find();
        if (request()->isGet())
        {
            $this->layoutModal();
            $this->assign('typeList',config('lottery_type'));
            $this->assign('info',$info);
            $this->assign('single_image',['img_url'=>$info['img_url']]);
            return $this->fetch();
        }

        if (request()->isAjax())
        {
            if(!$info){
                $this->ajaxError('无此商品或已删除');
            }
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );

            $data["title"] = trim(request()->param("title"));
            if(empty($data['title'])){
                $this->ajaxError('请输入奖名称');
            }

            $data["goods_title"] = trim(request()->param("goods_title"));
            if(empty($data['goods_title'])){
                $this->ajaxError('请输入商品名称');
            }

            $data["price_title"] = trim(request()->param("price_title"));
            if(empty($data['price_title'])){
                $this->ajaxError('请输入中奖提示词');
            }

            //商品缩略图
            $data["img_url"] = trim(request()->param("img_url"));
            if(empty($data['img_url'])){
                $this->ajaxError('请上传商品缩略图');
            }

            $data["type"] = intval(request()->param("type"));
            if(empty($data['type'])){
                $this->ajaxError('请选择商品类型');
            }

            $data["num"] = intval(request()->param("num"));
            if($data['num']<0){
                $this->ajaxError('商品数值最小1');
            }

            $data["gl"] = intval(request()->param("gl"));
            if($data['gl']<0){
                $this->ajaxError('中奖比重最小0');
            }

            $data["stock"] = intval(request()->param("stock"));
            if($data['stock']<0){
                $this->ajaxError('商品库存最小0');
            }

            //显示隐藏
            $data['is_visible'] = intval(request()->param('is_visible'));

            try
            {
                $save = Db::name("lottery")->where('id',$id)->update($data);
                $log = '编辑-抽奖商品-'.$id;
                if($save){
                    Message::admin_log(0, $log);
                    $this->ajaxSuccess($log.'成功');
                }else{
                    Message::admin_log(0, $log);
                    $this->ajaxError($log.'失败');
                }

            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除商品
    public function remove()
    {
        if (request()->isAjax())
        {
            //商品ID
            $id = request()->param("id");
            try
            {

                //更新商品
                $del = Db::name("lottery")
                    ->where("id", $id)
                    ->delete();
                $log = '删除-抽奖商品-'.$id;

                if($del){
                    Message::admin_log(0, $log.'成功');
                    $this->ajaxSuccess('商品删除成功');
                }else{
                    Message::admin_log(0, $log.'失败');
                    $this->ajaxError('商品删除失败');
                }
            }
            catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception=true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }

    //抽奖记录
    public function lists()
    {
        $where = [];

        $this->templateTitle('抽奖记录');

        //搜索条件-用户
        $user_condition = request()->param("user_condition");
        $this->assign("user_condition", $user_condition);
        if ($user_condition)
        {
            $where["us.username|us.selfphone|us.id"] = $user_condition;
        }

        $this->assign('typeList',config('lottery_type'));
        $type = request()->param('type');
        $this->assign('type',$type);
        if($type){
            $where['l.type']=intval($type);
        }

        //领取
        $status = request()->param('status');
        $this->assign('status',$status);
        if($status!=''){
            $where['l.status']=intval($status);
        }

        //发货
        $send_status = request()->param('send_status');
        $this->assign('send_status',$send_status);
        if($send_status!=''){
            $where['l.send_status']=intval($send_status);
        }

        //搜索条件-注册时间
        if (request()->has("time_range"))
        {
            //解析时间
            $timeRange = request()->param("time_range");
            $timeRange = explode(" ~ ", $timeRange);
            //模板渲染值
            $this->assign("range_start", ["time_range" => $timeRange[0]]);
            $this->assign("range_end", ["time_range" => $timeRange[1]]);

            $where['l.create_time'] = ["BETWEEN", [strtotime($timeRange[0] . " 00:00:00"),strtotime($timeRange[1] . " 23:59:59")]];

        }
        else
        {
            //模板渲染值
            $this->assign("range_start", ["time_range" => '2018-01-01']);
            $this->assign("range_end", ["time_range" => date("Y-m-d")]);
        }

        //获取评价列表
        $list = Db::name("lottery_list")
            ->alias('l')
            ->join('__USER__ us','us.id=l.uid','LEFT')
            ->where($where)
            ->order("l.id DESC")
            ->field('l.*,us.username as nick_name,us.selfphone as mobile')
            ->paginate(10);
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function send(){
        $order_id=input('id');
        $order = Db::name('lottery_list')
            ->alias('o')
            ->join('__USER__ u','u.id=o.uid','LEFT')
            ->where('o.id',$order_id)
            ->field('o.*,u.username nick_name,u.selfphone as umobile')
            ->find();
        if(request()->isGet()){
            $this->layoutModal();
            $this->assign('info',$order);
            $this->assign("range_start2", ["send_time" => date("Y-m-d H:i")]);
            return $this->fetch();
        }
        if(request()->isAjax()){
            try{
                if($order['status']!=1){
                    $this->ajaxError('会员未领取无法发货');
                }
                if($order['send_status']!=0){
                    $this->ajaxError('已发货勿重复发货');
                }

                $send_company = trim(input('send_company'));
                if(empty($send_company)){
                    $this->ajaxError('请输入快递公司名称');
                }
                $send_sn = trim(input('send_sn'));
                if(empty($send_sn)){
                    $this->ajaxError('请输入快递单号');
                }
                $send_time = trim(input('send_time'));
                $data = [
                    'send_status'=>1,
                    'send_company'=>$send_company,
                    'send_sn'=>$send_sn,
                    'send_time'=>empty($send_time)?now_datetime():strtotime($send_time)
                ];
                $save = Db::name('lottery_list')->where('id',$order_id)->update($data);
                if($save){
                    Message::admin_log(0, '确认发货-抽奖记录-'.$order_id);
                    $this->ajaxSuccess('确认发货成功');
                }else{
                    Message::admin_log(0, '确认发货-抽奖记录-'.$order_id);
                    $this->ajaxSuccess('确认发货失败');
                }

            }catch (\Exception $exception)
            {
                global $admin_has_exception;
                $admin_has_exception = true;
                $this->ajaxError($exception->getMessage());
            }
        }
    }
}